#include "client.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>


int registerFunc(int sockfd){
    char buff[1024] = {0};
    char username[64] = {0};
    //用于接收消息
    Msg m;
    //检查用户名是否存在
    while ((getchar()) != '\n');    //清空输入缓冲区
    while(1){
        printf("register username:\n");
        fgets(buff, sizeof(buff), stdin);
        buff[strlen(buff) - 1] = '\0';  //省略换行符

        sendCmd(sockfd, CMD_TYPE_REG1, buff); 

        getMsg(sockfd, &m);

        if(m.type == MSG_TYPE_DUPLICATE){
            printf("username already exists.\n");
        }else if(m.type == MSG_TYPE_SUCCESS){ //此用户名可使用
            strcpy(username, buff);
            break;
        }
    }

    printf("salt: %s\n", m.data);
    char salt[13] = {0};
    strcpy(salt, m.data);

    char passwd1[64], passwd2[64];
    while(1){
        //输入密码
        char* passwd = getpass("password:");
        strcpy(passwd1, passwd);
        passwd = getpass("password again:");
        strcpy(passwd2, passwd);
        if(!strcmp(passwd1, passwd2)){
            break;
        } else {
            printf("two different passwords.\n");
        }
    }

    //根据密码和盐值生成密文
    char *cry_password = crypt(passwd1, salt);

    //拼接data
    memset(buff, 0, sizeof(buff));
    sprintf(buff, "%s:%s:%s", username, salt, cry_password);

    sendCmd(sockfd, CMD_TYPE_REG2, buff);

    getMsg(sockfd, &m);
    if(m.type == MSG_TYPE_SUCCESS){
        printf("register successful.\n");
    }else{
        printf("register failed.\n");
    }
    exit(0);
    return 0;
}
